package com.example.demowebclientv1.controller;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/proxy")
public class ProxyController {

    private final WebClient webClient;

    public ProxyController(WebClient webClient) {
        this.webClient = webClient;
    }

    @RequestMapping("/**")
    public Mono<ResponseEntity<byte[]>> proxyRequest(
            @RequestHeader HttpHeaders headers,
            @RequestBody(required = false) byte[] body,
            HttpMethod method,
            HttpServletRequest  request) {

        // 构建目标URL（示例：将请求转发到新地址）
        String path = request.getRequestURI().replaceFirst("^/proxy", "");
        String targetUrl = "https://lowcode.yardezx.com" + path;

        // 移除可能触发WAF检测的请求头
        headers.remove("host");
        headers.remove("x-forwarded-for");

        return webClient.method(method)
                .uri(targetUrl)
                .headers(h -> {
                    h.putAll(headers);
                    // 添加伪装请求头
                    h.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...");
                })
                .bodyValue(body != null ? body : new byte[0])
                .exchangeToMono(response -> {
                    HttpHeaders responseHeaders = new HttpHeaders();
                    responseHeaders.addAll(response.headers().asHttpHeaders());
                    return response.bodyToMono(byte[].class)
                            .map(b -> new ResponseEntity<>(b, responseHeaders, response.statusCode()));
                })
                .onErrorResume(e -> Mono.just(
                        ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                                .body(("Proxy error: " + e.getMessage()).getBytes())
                ));
    }
}